/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package echoserverssl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

/**
 *
 * @author Maciek
 */
public class EchoServerSSL {

    /**
     * @param args the command line arguments
     */
    
    private static SSLServerSocketFactory getFactory( File pKeyFile, String pKeyPassword ) throws NoSuchAlgorithmException, KeyStoreException, FileNotFoundException, IOException, CertificateException, UnrecoverableKeyException, KeyManagementException {
	  KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
	  KeyStore keyStore = KeyStore.getInstance("JKS");
	 
	  InputStream keyInput = new FileInputStream(pKeyFile);
	  keyStore.load(keyInput, pKeyPassword.toCharArray());
	  keyInput.close();
	  keyManagerFactory.init(keyStore, pKeyPassword.toCharArray());
          
	  SSLContext context = SSLContext.getInstance("TLS");
          
	  context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
	  
            
	  return context.getServerSocketFactory();
          
          
    }
    public static void main(String[] args) {
        try {
            SSLServerSocketFactory sslserversocketfactory =
                    (SSLServerSocketFactory) getFactory(new File("pkwkeystore.jks"),"bskbsk");
            SSLServerSocket sslserversocket =
                    (SSLServerSocket) sslserversocketfactory.createServerSocket(9999);
              sslserversocket.setUseClientMode(false);
            
            SSLSocket sslsocket = (SSLSocket) sslserversocket.accept();
       
            InputStream inputstream = sslsocket.getInputStream();
            InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
            BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

            String string = null;
            while ((string = bufferedreader.readLine()) != null) {
                System.out.println("server" + string);
                System.out.flush();
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}
